#include "client.h"




int cutTail(char *path, char *left, char *right) {
    
    char tmp[1024] = {0};
    memcpy(tmp, path, strlen(path));
    char *p = strtok(tmp, "/");
    while (1) {

        char *tmp = strtok(NULL, "/");
        if (tmp == NULL) {
            memcpy(right, p, strlen(p) + 1);
            left[strlen(path) - strlen(right) - 1] = '\0';
            if (strlen(path) - strlen(right) - 1 == 0) {
                left[0] = '/';
            }
            break;
        }
        p = tmp;
    }
    return 0;
}


int cutCmd(char *input,char *cmd,char *path1,char *path2){
    char tmp[1024] = {0};
    char *p1, *p2, *p3;
    memcpy(tmp,input,strlen(input)-1);
    tmp[strlen(input)] = '\0';
    p1 = strtok(tmp," ");
    memcpy(cmd, p1, strlen(p1) + 1);
    p2 = strtok(NULL," ");
    if(p2 == NULL) {
       return 1;
    }
    memcpy(path1, p2, strlen(p2) + 1);
    p3 = strtok(NULL," ");
    if(p3 == NULL){
        return 1;
    }
    memcpy(path2, p3, strlen(p3) + 1);
    if (strtok(NULL," ")) {
        return 0;
    }
    return 1;
}

int checkCmd(const char *cmd){
    if(strcmp(cmd,"cd")==0||strcmp(cmd,"ls")==0||strcmp(cmd,"gets")==0||strcmp(cmd,"puts")==0||strcmp(cmd,"remove")==0||strcmp(cmd,"rmdir")==0||strcmp(cmd,"mkdir")==0||strcmp(cmd,"pwd")==0){
        return 1;
    }
    return 0;
}

int checkArguments(const char *cmd, const char *path1, const char *path2, int cutRet) {
    if (!checkCmd(cmd)) {
        printf("%s: command not found\n", cmd);
        return 0;
    }
    if (!cutRet) {
        printf("%s: too many arguments\n", cmd);
        return 0;
    }
    if ((strcmp(cmd, "pwd") == 0 || strcmp(cmd, "ls") == 0)&& path1 && strlen(path1) != 0) {
        printf("%s: too many arguments\n", cmd);
        return 0;
    } else if ((strcmp(cmd, "mkdir") == 0 || strcmp(cmd, "rmdir") == 0 || strcmp(cmd, "remove") == 0 || strcmp(cmd, "cd") == 0) && strlen(path2) != 0) {
        printf("%s: too many arguments\n", cmd);
        return 0;
    } else if ((strcmp(cmd, "mkdir") == 0 || strcmp(cmd, "rmdir") == 0 || strcmp(cmd, "remove") == 0) && strlen(path1) == 0) {
        printf("%s: need an argument\n", cmd);
        return 0;
    } else if (strcmp(cmd, "puts") == 0 || strcmp(cmd, "gets") == 0) {

        if(!(path1 && strlen(path1)>0 && path2 && strlen(path2) > 0)){
            printf("%s: need two arguments\n", cmd);
            return 0;

        }
           }
    if (strcmp(cmd, "puts") == 0) {
        int ret = open(path1, O_RDWR);
        if(ret == -1) {
            printf("puts: no such file\n");
            return 0;
        }
        close(ret);
    }
    return 1;
}
